%% Copyright
-module(search_handler).
-author("").

%% API
-export([init/3, allowed_methods/2, content_types_provided/2, search/2]).

init(_Transport, _Req, []) ->
  {upgrade, protocol, cowboy_rest}.

allowed_methods(Req, State) ->
  {[<<"GET">>], Req, State}.

content_types_provided(Req, State) ->
  {[{{<<"application">>, <<"json">>, []}, search}],
    Req, State}.

search(Req, State) ->
  {SearchType, Req1} = cowboy_req:binding(search_type, Req),
  {Parameters, Req2} = cowboy_req:qs_vals(Req1),

  FoldFun = fun({<<"key">>, Value}, Acc) -> [Value | Acc];
               ({_Name, _Value}, Acc) -> Acc
            end,
  KeyValues = lists:foldl(FoldFun, [], Parameters),

  {{PageIndex, PageSize}, Req3} = http_util:get_paging_parameters(Req2),

  case SearchType of
    <<"prodid">> ->
      get_search_response(Req3, State, key, KeyValues, PageIndex, PageSize);
    <<"tag">> ->
      get_search_response(Req3, State, tag, KeyValues, PageIndex, PageSize);
    <<"name">> ->
      get_search_response(Req3, State, name, KeyValues, PageIndex, PageSize);
    _ ->
      {ok, Req5} = cowboy_req:reply(404, Req3),
      {true, Req5, State}
  end.

get_search_response(Req, State, _SearchType, [], _PageIndex, _PageSize) ->
  {ok, Req1} = cowboy_req:reply(400, [], "Invalid key parameter", Req),
  {true, Req1, State};

get_search_response(Req, State, SearchType, Keys, PageIndex, PageSize) ->
  Result = search_product(SearchType, Keys, PageIndex, PageSize),
  {jsx:encode(Result), Req, State}.

search_product(key, Keys, _PageIndex, _PageSize) ->
  {ok, Products} = cn2p_catalog:search_product_by_id(Keys),
  [{<<"products">>, Products}];

search_product(tag, Keys, PageIndex, PageSize) ->
  {ok, SearchResult} = cn2p_catalog:search_product_by_tag(lists:nth(1, Keys), PageIndex, PageSize),
  SearchResult;

search_product(name, Keys, PageIndex, PageSize) ->
  {ok, SearchResult} = cn2p_catalog:search_product_by_name(lists:nth(1, Keys), PageIndex, PageSize),
  SearchResult.